import { $cache } from '@/plugins'

class CachedVariableManager<T> {
  public value: T | undefined | null
  public cacheKey: string
  constructor(cacheKey: string, isSession: boolean = false) {
    this.cacheKey = cacheKey
    if (isSession) this.clearValue()
  }
  getValue(): T | null {
    if (this.value != null) return this.value
    const value = $cache.get(this.cacheKey)
    return value != null ? (this.value = value) : null
  }
  // expirationTime 是到期时的时间戳
  setValue(value: T, expirationTime?: number) {
    if (value == null) return
    this.value = value
    $cache.set(this.cacheKey, value, expirationTime ? { expires: expirationTime } : {})
  }
  clearValue() {
    $cache.remove(this.cacheKey)
    this.value = undefined
  }
}
export default CachedVariableManager
